import cloneDeep from 'lodash.clonedeep';
import { ComponentInfoType, ComponentsStateType } from '.';

export function getNextSelectedId(fe_id: string, componentList: ComponentInfoType[]): string {
  const visibleComponentList = componentList.filter((component) => !component.isHidden);
  const index = visibleComponentList.findIndex((component) => component.fe_id === fe_id);
  if (index === -1) {
    return '';
  }
  let newSelectedId = '';
  const length = visibleComponentList.length;
  if (length <= 1) {
    newSelectedId = '';
  } else {
    //删除最后一个,选中上一个
    if (index === length - 1) {
      newSelectedId = visibleComponentList[index - 1].fe_id;
    } else {
      newSelectedId = visibleComponentList[index + 1].fe_id;
    }
  }
  return newSelectedId;
}

export function insertNewComponent(state: ComponentsStateType, newComponent: ComponentInfoType) {
  const { selectedId, componentList } = state;
  const index = componentList.findIndex((component) => component.fe_id === selectedId);
  if (index !== -1) {
    state.componentList.splice(index + 1, 0, newComponent);
  } else {
    state.componentList.push(newComponent);
  }
}

export function arrayMove<T>(array: T[], from: number, to: number): T[] {
  if (from < 0 || to >= array.length) {
    console.log('参数错误');
    // 终止执行
    throw new Error('参数错误: from:' + from + ', to:' + to);
  }
  const newArr = cloneDeep(array);
  const item = newArr.splice(from, 1);
  newArr.splice(to, 0, ...item);
  return newArr;
}
